package com.xcw.bos.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.activiti.engine.ProcessEngine;
import org.activiti.engine.impl.persistence.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xcw.bos.dao.IRoleDao;
import com.xcw.bos.dao.IUserDao;
import com.xcw.bos.domain.Role;
import com.xcw.bos.domain.User;
import com.xcw.bos.service.IUserService;
import com.xcw.bos.utils.MD5Utils;

@Service
@Transactional
public class UserServiceImpl implements IUserService{
    @Resource 
    private IRoleDao roleDao;
    @Autowired
    private ProcessEngine processEngine;
	public UserServiceImpl(){
		System.out.println("Service创建了。。。。。。");
	}
	
	@Autowired
	private IUserDao userDao;
	public User login(User model) {
		String password = model.getPassword();
		password = MD5Utils.md5(password);
		List<User> list = userDao.findByNamedQuery("findByUserNameAndPassword",
				model.getUsername(), password);
		if (list != null && list.size() > 0){
			return list.get(0);
		}
		return null;
	}

	//根据id修改密码
	public void editPassword(String password, String id) {
		password = MD5Utils.md5(password);
		userDao.executeByNamedQuery("editPassword", password, id);
		
	}
	
	public void save(User user, String[] roleIds){
		String password = user.getPassword();
		password = MD5Utils.md5(password);
		user.setPassword(password);
		userDao.save(user);//持久对象
		
		org.activiti.engine.identity.User actUser = new UserEntity();
		actUser.setId(user.getId());
		processEngine.getIdentityService().saveUser(actUser);
		if(roleIds != null && roleIds.length > 0){
			for(String roleId : roleIds){
				//构造脱管角色对象
				//Role role = new Role();
				//role.setId(roleId);
				Role role = roleDao.findById(roleId);
				user.getRoles().add(role);//用户关联角色
				processEngine.getIdentityService().createMembership(actUser.getId(), role.getName());
			}
		}
		
	}
	
	public List<User> findAll(){
		return userDao.findAll();
	}
	
	public User findById(String id){
		return userDao.findById(id);
	}

}
